/**
 * require本模块需要的Node.js模块
 */
var sys = require('util'),
  http = require('http'),
  fs = require('fs'),
  url = require('url'),
  path = require('path');
mmieConf = getMmieConf();

exports.getStaticFile = function(pathname, res) {
  pathname = decodeURI(pathname); //中文解码
  //var pointPosition = pathname.lastIndexOf('.'),mimeString = pathname.substring(pointPosition + 1),
  var extname = path.extname(pathname); // '.css'
  // console.log(extname.substr(1) + ':' + extname.substring(1) + ':' + extname.slice(1)); // 'css:css:css'
  extname = extname ? extname.slice(1) : '';
  var readPath = STATIC + pathname;
  var mmieType = mmieConf[extname] ? mmieConf[extname] : 'text/plain';
  fs.exists(readPath, function(exists) {
    if (!exists) {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.write('This request URL ' + pathname + ' was not found on this server!');
      res.end();
    } else {
      fs.readFile(readPath, 'binary', function(err, file) {
        if (err) {
          res.writeHead(500, { 'Content-Type': 'text/plain' });
          res.end(err);
        } else {
          res.writeHead(200, { 'Content-Type': mmieType });
          res.write(file, 'binary');
          res.end();
        }
      });
    }
  });
};

function getMmieConf() {
  var readPath = CONF + '/mmie_type.json';
  var mmieStr = fs.readFileSync(readPath);
  var mmieObj = JSON.parse(mmieStr);
  return mmieObj;
}
